from django import forms
import re
from users.models import UserProfile,Grade,GradeStudent
from course.models import Course,Lesson,Video,PaperList
from operation.models import Sign


class LoginForm(forms.Form):
    username = forms.CharField(required=True,
                               widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入账号！"}))
    password = forms.CharField(required=True,
                               widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "请输入密码！"}),
                               min_length=5)


class RegisterForm(forms.Form):
    username = forms.CharField(required=True,
                               widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入用户名！"}))
    email = forms.EmailField(required=True,
                             widget=forms.EmailInput(attrs={"class": "form-control", "placeholder": "请输入邮箱！"}))
    mobile = forms.CharField(required=True,
                             widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入手机号！"}))
    password = forms.CharField(required=True,
                               widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入密码！"}),
                               min_length=5)

    def clean_mobile(self):
        """
        验证手机号码是否合法
        """
        mobile = self.cleaned_data['mobile']
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|176\d{8}$"
        p = re.compile(REGEX_MOBILE)
        if p.match(mobile):
            return mobile
        else:
            raise forms.ValidationError(u"手机号码非法", code="mobile_invalid")

    def clean_username(self):
        username = self.cleaned_data['username']
        users = UserProfile.objects.filter(username=username)
        if users:
            raise forms.ValidationError(u"用户名已存在", code="username_invalid")
        else:
            return username


class GradeForm(forms.Form):
    grade_name = forms.CharField(required=True,min_length=3,widget=forms.TextInput(
        attrs={"class":"form-control","placeholder":"请输入班级名称！"}
    ),label="班级名称")

    def clean_grade_name(self):
        grade_name = self.cleaned_data["grade_name"]
        grades = Grade.objects.filter(GradeName=grade_name)
        if grades:
            raise forms.ValidationError(u"班级名已存在",code="grade_name_invalid")
        else:
            return grade_name


class CourseForm(forms.Form):
    teacher_name = [(1,"python")]
    name = forms.CharField(required=True,min_length=3,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入班级名称！"}
    ),label="课程名")

    desc = forms.CharField(required=True,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入课程描述！"},
    ),label="课程描述")

    detail = forms.CharField(required=True,widget=forms.Textarea(
        attrs={"class": "form-control", "placeholder": "请输入课程详情！"},
    ),label="课程详情")

    learn_times = forms.IntegerField(min_value=0,required=True,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入学习时长！"},
    ),label="学习时长")

    students = forms.IntegerField(min_value=0,required=True,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入学习人数！"},
    ),label="学习人数")

    fav_nums = forms.IntegerField(min_value=0,required=True,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入学习人数！"},
    ),label="收藏人数")

    image = forms.FileField(label="封面图片")

    click_nums = forms.IntegerField(min_value=0,required=True,widget=forms.NumberInput(
        attrs={"class": "form-control", "placeholder": "请输入点击数！"},
    ),label="点击数")

    tag = forms.CharField(required=True,max_length=10,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入课程标签！"},
    ),label="课程标题")

    you_need_know = forms.CharField(required=True,max_length=300,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入你需要知道！"},
    ),label="你需要知道")

    teacher_tell = forms.CharField(required=True,max_length=300,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入教师告诉你！"},
    ),label="教师告诉你")

    grade = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择班级！"},
    ),label="班级",choices=teacher_name)

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.fields["grade"].choices = Grade.objects.filter(teacher=user).values_list("id","GradeName")


class ResourceForm(forms.Form):
    name = forms.CharField(required=True,max_length=300,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入名称"}
    ),label="名称")
    downloads = forms.FileField(required=True,label="资料")
    course = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择课程！"}
    ),label="课程")

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields["course"].choices = Course.objects.filter(grade__teacher=user).values_list("id","name")


class GradeStudentForm(forms.Form):
    grade = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择班级！"},
    ),label="班级")
    user = forms.CharField(required=True,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入学生姓名！"}
    ),label="学生")

    def clean_user(self):
        user = self.cleaned_data['user']
        users = UserProfile.objects.filter(username=user)
        if not users:
            raise forms.ValidationError(u"用户名不存在", code="username_invalid")
        print(self.cleaned_data)
        user1 = GradeStudent.objects.filter(user__username=user,grade_id=self.cleaned_data["grade"])
        print(user1)
        if user1:
            raise forms.ValidationError(u"用户名存在于班级中", code="username_invalid")
        return user

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.fields["grade"].choices = Grade.objects.filter(teacher=user).values_list("id","GradeName")


class LessonForm(forms.Form):
    name = forms.CharField(required=True,min_length=3,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入章节名！"}
    ),label="章节名")
    course = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择课程！"}
    ),label="课程")

    def clean_name(self):
        name = self.cleaned_data['name']
        lessons = Lesson.objects.filter(name=name)
        if lessons:
            raise forms.ValidationError(u"章节已存在",code="lesson_name invalid")
        return name

    def __init__(self,user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["course"].choices = Course.objects.filter(grade__teacher=user).values_list("id", "name")


class VideoForm(forms.Form):
    lesson = forms.ChoiceField(required=True,label="章节",widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择章节！"}
    ))
    url = forms.CharField(required=True,min_length=5,label="视频链接(七牛云)",widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入视频链接！"}
    ))
    name = forms.CharField(required=True,min_length=5,label="视频名称",widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入视频名称！"}
    ))
    learn_times = forms.IntegerField(required=True,widget=forms.NumberInput(
        attrs={"class": "form-control", "placeholder": "请输入学习时长！"}
    ))

    def clean_name(self):
        name = self.cleaned_data["name"]
        if Video.objects.filter(name=name):
            raise forms.ValidationError("视频已存在",code="video_invalid")
        return name

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args,**kwargs)
        grade_ids = Grade.objects.filter(teacher=user).values_list("id")
        self.fields["lesson"].choices = Video.objects.filter(lesson__course__grade_id__in=grade_ids).values_list("id","name")


class MessageForm(forms.Form):
    grade = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择班级！"},
    ),label="班级")
    title = forms.CharField(required=True,min_length=5,widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入标题！"},
    ),label="消息标题")
    content = forms.CharField(required=True,widget=forms.Textarea(
        attrs={"class": "form-control", "placeholder": "请输入消息详情！"},
    ),label="消息详情")

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.fields["grade"].choices = Grade.objects.filter(teacher=user).values_list("id","GradeName")


class ExamForm(forms.Form):
    course = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择课程！"}
    ),label="课程")
    name = forms.CharField(required=True,min_length=3,label="考试名称",widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入考试名称！"}
    ))

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields["course"].choices = Course.objects.filter(grade__teacher=user).values_list("id","name")

    def clean_name(self):
        name = self.cleaned_data["name"]
        if PaperList.objects.filter(name=name):
            raise forms.ValidationError("考试已存在",code="exam invalid")
        return name


class SignForm(forms.Form):
    grade = forms.ChoiceField(required=True,widget=forms.Select(
        attrs={"class": "form-control", "placeholder": "请选择班级！"},
    ),label="班级")
    name = forms.CharField(required=True,min_length=3,max_length=10,label="签到名称",widget=forms.TextInput(
        attrs={"class": "form-control", "placeholder": "请输入签到名称！"}
    ))

    def clean_name(self):
        name = self.cleaned_data["name"]
        if Sign.objects.filter(sign_name=name):
            raise forms.ValidationError("签到已存在",code="sign invalid")
        return name

    def __init__(self,user,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.fields["grade"].choices = Grade.objects.filter(teacher=user).values_list("id","GradeName")
